package org.onionframework.persistence.dao.projection;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.SessionFactoryImpl;
import org.onionframework.core.Onion;
import org.onionframework.persistence.dao.functions.DateFormatFunction;
import org.onionframework.persistence.dao.functions.date.HSQLDateFormatFunction;
import org.onionframework.persistence.dao.functions.date.MYSQLDateFormatFunction;
import org.onionframework.persistence.dao.functions.date.OracleDateFormatFunction;

public class DateStringUtils {

	private static SessionFactoryImplementor factory = Onion.getBean(SessionFactoryImpl.class);

	private static Map<String,DateFormatFunction> functions = new HashMap<String,DateFormatFunction>();
	
	static{
		functions.put("MYSQL", new MYSQLDateFormatFunction());
		functions.put("HSQL", new HSQLDateFormatFunction());
		functions.put("ORACLE", new OracleDateFormatFunction());
	}
	
	public static void registerFunction(String dialect, DateFormatFunction function){
		functions.put(dialect, function);
	}
	
	private DateFormatFunction function;
	
	private String pattern;
	
	public DateStringUtils(String pattern) {
		super();
		this.pattern = pattern;
	}

	public String toSql(String column){
		if(this.function == null){
			String dialect = factory.getDialect().getClass().getSimpleName();
			for(Map.Entry<String, DateFormatFunction> entry : functions.entrySet()){
				if(dialect.toLowerCase().indexOf(entry.getKey().toLowerCase()) > -1){
					this.function = entry.getValue();
					break;
				}
			}
			
			if(this.function == null)
				throw new RuntimeException("DateString projection is not supported for your current Dialect.");
		}
		
		return this.function.toSQL(column, this.pattern);
		
	}
}
